package com.kt.thread.demo;

import java.util.Random;
import java.util.concurrent.CopyOnWriteArrayList;

/**
 * Created by tangwy on 2016/3/30.
 */
public class CopyOnWriteArrayListTest {
    private  final CopyOnWriteArrayList<Integer> list = new CopyOnWriteArrayList<Integer>();
    public CopyOnWriteArrayListTest(){
        list.add(1);
    }
    public  void read() {
        /*Iterator<Integer> iterator=list.iterator();
        while (iterator.hasNext()){
            System.out.println(iterator.);
        }*/
        new Thread(new Runnable() {
            @Override
            public void run() {
                while (true) {
                    for(int i=0;i<list.size();i++){
                        System.out.println("线程：" + Thread.currentThread().getName() + ",获取list的值为:" + list.get(i));
                    }
                    try {
                        Thread.sleep(5000);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }
            }
        }).start();
    }

    public  void write() {
        final Random random = new Random();
        new Thread(new Runnable() {
            @Override
            public void run() {
                while (true) {
                    int i = random.nextInt();
                    System.out.println("线程：" + Thread.currentThread().getName() + ",设置list的值为:" + i);
                    list.add(i);
                    try {
                        Thread.sleep(2000);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }
            }
        }).start();
        new Thread(new Runnable() {
            @Override
            public void run() {
                while (true) {
                    int i = random.nextInt();
                    System.out.println("线程：" + Thread.currentThread().getName() + ",设置list的值为:" + i);
                    list.add(i);
                    try {
                        Thread.sleep(2000);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }
            }
        }).start();
    }

    public static void copuArrayTest() {

    }
}
